package com.defysoft.waukids.intro;

import java.util.ArrayList;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Custom_Data_Type.Bc_Student_Cus;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.PublicConstant;
import com.defysoft.waukids.R;

public class Slide_DeleteStudent_A extends BaseActivity implements OnClickListener {

	ListView listView;
	Adapter_DeleteSelectStudent_L adapter;
	ArrayList<Bc_Student_Cus> list;
	Toolbar toolbar;
	private final int SELECT_STUDENT = 1;	//메인스레드
	private final int DELETE_THREAD = 2;	//자녀삭제 스레드.
	private final int SUCCESS_DELETE = 7;
	private final int FAIL_DELETE= 8;
	private final int NONE_STUDENT = 9;
	private final int SUCCESS_SEARCH= 10;
	String PK_Mem_Email;	//맴버메일, 학생코드
	int PK_Stu_Code;
	
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.slide_deletestudent_a);
		setStartData();

	}
	
	@Override
	public void setStartData() {
		super.setStartData();
		PK_Mem_Email = getIntent().getStringExtra("PK_Mem_Email");	//수정이면 값이 있음.
		toolbar = (Toolbar)findViewById(R.id.SLIDE_DELETESTUDENT_TOOL);
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {finish();}
		});
		listView=(ListView)findViewById(R.id.SLIDE_DELETESTUDENT_LIST);
		startNetwork(SELECT_STUDENT);		
	}
	
	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		if (firstThread != null) {firstThread.interrupt();}
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case SELECT_STUDENT:
					mainThread();
					break;
				case DELETE_THREAD:
					deleteThread();
					break;
				}
			}
		});
		firstThread.start();
	}
	
	protected void mainThread() {
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_SELECT_MYSTUDENT,"email="+PK_Mem_Email));
			if (jsonObject.getBoolean("success")) {	
				list=JsonParser.SelectMyStudent(jsonObject.getString("payload"));

				onNetworkCallback(SUCCESS_SEARCH,"" );
			} else {
				onNetworkCallback(NONE_STUDENT, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, "main"+e.toString());
		};		
	}
	
	protected void deleteThread() {
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_DELETE_MYSTUDENT,"FK_Mem_Stu_Con_Code="+PK_Mem_Email+"&FK_Stu_Stu_Con_Code="+PK_Stu_Code));
			if (jsonObject.getBoolean("success")) {	
				list=JsonParser.SelectMyStudent(jsonObject.getString("payload"));

				onNetworkCallback(SUCCESS_DELETE,"" );
			} else {
				onNetworkCallback(FAIL_DELETE,  jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, "main"+e.toString());
		};			
	}


	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_LONG).show();			
			break;
		case SUCCESS_SEARCH:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			adapter=new Adapter_DeleteSelectStudent_L();
			listView.setAdapter(adapter);		
			break;
		case NONE_STUDENT:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(Slide_DeleteStudent_A.this, "등록된 자녀가 없습니다. 자녀코드를 등록해주세요", Toast.LENGTH_LONG).show();
			break;
		case SUCCESS_DELETE:
			Toast.makeText(Slide_DeleteStudent_A.this, "삭제완료", Toast.LENGTH_SHORT).show();
			startActivity(new Intent(Slide_DeleteStudent_A.this, Intro_Intro_A.class));
			finish();
			break;
		case FAIL_DELETE:
			Toast.makeText(Slide_DeleteStudent_A.this, (String) _message.obj, Toast.LENGTH_SHORT).show();
			break;
		
		}
	}
	@Override
	public void onClick(View v) {

	}
	
	 class Adapter_DeleteSelectStudent_L extends ArrayAdapter<String> {
		public Adapter_DeleteSelectStudent_L() {
			super(Slide_DeleteStudent_A.this, android.R.layout.simple_list_item_1);
		}
		@Override
		public int getCount() {
			return list.size();
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Holder holder;
			final int pos = position;			
			if (convertView == null) {
				holder = new Holder();
				convertView = getLayoutInflater().inflate(R.layout.select_student_row,
						null);
				holder.tv1 = (TextView) convertView
						.findViewById(R.id.SELECT_STUDENT_NAME);
				holder.tv2 = (TextView) convertView
						.findViewById(R.id.SELECT_STUDENT_CLASS);
				holder.tv3 = (TextView) convertView
						.findViewById(R.id.SELECT_STUDENT_BIRTH);
				holder.iv = (WebView) convertView
						.findViewById(R.id.SELECT_STUDENT_IMG);
				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}
			holder.tv1.setText(list.get(position).Stu_Name + "어린이");
			holder.tv2.setText(list.get(position).classname);
			holder.tv3.setText(list.get(position).Stu_Birth);
			holder.iv.setVerticalScrollBarEnabled(false);
			holder.iv.setVerticalScrollbarOverlay(false);
			holder.iv.setHorizontalScrollBarEnabled(false);
			holder.iv.setHorizontalScrollbarOverlay(false);
			holder.iv.setInitialScale(100);

			if ( list.get(pos).Stu_Photo == null||list.get(pos).Stu_Photo.length()<5) {// 이미지 파일이 없으면 앱내에서 지정된 이미지를 뿌려주고
				holder.iv.setBackgroundColor(0);
				holder.iv.setBackgroundResource(R.drawable.perm_group_personal_info);
			} else {// 이미지 파일이 있으면
				holder.iv.loadDataWithBaseURL(null,
						creHtmlBody(PublicConstant.URI_STUDENDPHOTO
								+ list.get(pos).Stu_Photo), "text/html", "utf-8", null);
			}
			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) { // 아린이 눌림.
					AlertDialog.Builder builder = new AlertDialog.Builder(
							Slide_DeleteStudent_A.this);
					builder.setMessage(
							"자녀를 삭제 하겠습니까?\n자녀를 다시 등록 하려면,\n유치원에서 자녀코드를 다시 받으셔야 합니다.")
							.setCancelable(false)
							.setPositiveButton("네",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog,
												int which) {
											PK_Stu_Code = list.get(pos).PK_Stu_Code;
											startNetwork(DELETE_THREAD);
											dialog.cancel();
										}
									})
							.setNegativeButton("아니오",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog,
												int which) {
											dialog.cancel();
										}
									});
					AlertDialog alert = builder.create();
					alert.show();
				}
			});
			return convertView;
		}

		class Holder {
			TextView tv1;
			TextView tv2;
			TextView tv3;
			WebView iv;
		}

		public String creHtmlBody(String imagUrl) {
			StringBuffer sb = new StringBuffer("<HTML>");
			sb.append("<HEAD>");
			sb.append("</HEAD>");
			sb.append("<BODY  style='margin: 0; padding: 0'>");
			sb.append("<img width=\"100%\" height=\"100%\" src=\"" + imagUrl
					+ "\">");
			sb.append("</BODY>");
			sb.append("</HTML>");

			return sb.toString();
		}
	}

}
